﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ShakeScreen : MonoBehaviour
{
    // Start is called before the first frame update
    public float shakeDuration = 0.12f;
    private float shakeStartTime;
    private Vector3 shakeStartCameraPosition;
    public float shakeRange = 0.04f;
    public float shakeInterval = 0.02f;
    public float shakeCdTime;
    private Camera _mainCamera;
    void Start()
    {
        _mainCamera = WorldCameraManager.GetInstance().GetCamera();
    }
    public void Shake()
    {
        if (_mainCamera == null)
        {
            _mainCamera = WorldCameraManager.GetInstance().GetCamera();
        }
        shakeStartTime = Time.time;
        shakeStartCameraPosition = _mainCamera.transform.position;
    }

    public void StopShake()
    {
        if (shakeStartTime != 0)
        {
            if (_mainCamera)
            {
                _mainCamera.transform.position = shakeStartCameraPosition;
            }
            shakeStartTime = 0;
        }
    }
    
    // Update is called once per frame
    void Update()
    {
        if (_mainCamera == null)
        {
            return;
        }
        
#if UNITY_EDITOR
        if (Input.GetKeyDown(KeyCode.Space))
        {
            shakeStartTime = Time.time;
            shakeStartCameraPosition = _mainCamera.transform.position;
        }
#endif

        if (shakeStartTime != 0)
        {
            if (Time.time - shakeStartTime >= shakeDuration)
            {
                //battlePerlin.m_AmplitudeGain = 1;
                //battlePerlin.m_FrequencyGain = 1;
                _mainCamera.transform.position = shakeStartCameraPosition;
                shakeStartTime = 0;
                shakeCdTime = 0;
            }
            else
            {
                if (Time.time >= shakeCdTime)
                {
                    float xOffset = UnityEngine.Random.Range(-1f, 1f) * shakeRange;
                    float yOffset = UnityEngine.Random.Range(-1f, 1f) * shakeRange;
                    Vector3 worldOffset = Quaternion.AngleAxis(transform.localEulerAngles.y, Vector3.up) * new Vector3(xOffset, 0, yOffset);
                    var newPosition = shakeStartCameraPosition + worldOffset;

                    //cameraFocusToken.transform.position = shakeStartCameraPosition;
                    var lastFrameDiff = _mainCamera.transform.position - shakeStartCameraPosition;
                    var screenPoint = _mainCamera.WorldToScreenPoint(newPosition + lastFrameDiff) -
                                      new Vector3(Screen.width / 2, Screen.height / 2, 0);
                    _mainCamera.transform.position = newPosition;
                    shakeCdTime = Time.time + shakeInterval;
                }

            }
        }
    }
}
